import { WeApp } from '../../../common/common';
import { config } from '../../../etc/config';
import * as __ from '../../../assets/plugins/underscore.js';
import httpClient from '../../../common/http-client';
import { ShopCart } from '../../../model/order';
import tools from '../../../common/tools';
import wxService from '../../../common/wxService'
import * as wux from '../../../assets/components/wux'
import utils from '../../../utils/utils';
import { UserAuth } from '../../../common/auth';
import { MlcEnum } from '../../../model/enum';

const app = getApp() as WeApp;
interface ICartItem1 {
    key?: string,
    datas?: Array<ShopCart>,
    selected?: boolean,
    length?: number
}
interface CartListPageData {
    carts: {
        items?: ShopCart,
        total?: number,
        selectedCount?: number
    },
    isSelectedAll?: boolean,
    startX?: number,
    startY?: number,
    isTouchMove?: boolean,
    orderId?: string
}


interface CartListPage extends IPage {
}

class CartListPage {
    private drive: wx.GetSystemInfoResult = wx.getStorageSync(config.storageNames.systemInfo);
    private isIos = this.drive.system.toLocaleLowerCase().indexOf('ios') > -1;
    public data: CartListPageData = {
        carts: {
            total: 0,
            selectedCount: 0,
        }
    }

    public onLoad(options) {
        wxService.showLoading('加载中');
    }

    public onShow() {
        this.setData({
            'isSelectedAll': false,
        });
        const orderId = wx.getStorageSync(config.storageNames.cart_order_id)
        let param = {};
        if (orderId) {
            param['orderId'] = orderId;
        }
        wx.removeStorageSync(config.storageNames.cart_order_id);
        this.getCarts(param).then(() => {
            wx.hideLoading();
        });
    }

    public getCarts(param?) {
        return httpClient.get<ShopCart>(tools.buildUrl(config.shopCart.shopcar_get, param))
            .then((res) => {
                const prop = wux.prompt.init('msg1', {
                    title: '',
                    text: '这里还没有商品哦，快去逛逛吧！',
                    icon: 'http://r.59im.com/wx/tips/lack_without_cart_icon@2x.png'
                });
                if (!res.values || !res.values.length) {
                    prop.show();
                } else {
                    prop.hide()
                }
                const that = this;
                __.each(res.values, function (item) {
                    item['isTouchMove'] = false;
                })
                this.setData({
                    'carts.items': res.values
                });
                this.getTotalPrice();
            }).catch(e => {
                utils.loadError(() => {
                    this.getCarts();
                })
            })
    }

    checkedKeyItem(e) {
        const that = this;
        const index = e.currentTarget.dataset.index;
        const carts = this.data.carts.items;
        let cart = carts[index];
        const checkedStatus = !cart.selected;
        __.each(cart.datas, (item: {
            key?: string,
            datas?: Array<ShopCart>,
            selected?: boolean
        }) => {
            item.selected = checkedStatus;
        });
        cart.selected = checkedStatus;
        this.setData({ 'carts.items': carts });
        this.getTotalPrice();
        this.setCheckedAll();
    }

    checkedStandardItem(e) {
        const index = e.currentTarget.dataset.index;
        const carts = this.data.carts.items;
        let item = carts[index];
        if (!item.selected) {
            // if (!item.isSale) {
            //     utils.showToastErr(`当前商品暂未销售`);
            //     return;
            // }            
        }
        item.selected = !item.selected;
        this.setData({ 'carts.items': carts });
        this.getTotalPrice();
        this.setCheckedAll();
    }

    public selectAll(e) {
        const that = this;
        let isSelectedAll = !this.data.isSelectedAll;
        let carts = this.data.carts.items;
        __.each(carts, function (item: ShopCart) {
            item.selected = isSelectedAll
        });
        this.setData({
            'isSelectedAll': isSelectedAll,
            'carts.items': carts
        });
        this.getTotalPrice();
    }


    setCheckedAll() {
        const items = this.data.carts.items;
        this.setData({
            'isSelectedAll': items.length === __.where(items, { 'selected': true }).length
        })
    }

    submitOrder(e) {
        if (this.data.carts.total == 0) {
            utils.showToastErr('您没选择商品哦!');
            return;
        }
        if(!UserAuth.checkIsBuy()){
            return;
        }
        wx.setStorageSync('confirmOrder', this.getSelectedGoods())
        wxService.navigateTo('/pages/order/confirm/index')
    }

    public delCartItem(e) {
        const target = e.currentTarget.dataset;
        wxService.showModal({ content: '是否确认删除此商品？', confirmColor: '#1972ff' })
            .then((res: wx.ShowModalResult) => {
                if (res.confirm) {
                    httpClient.post(config.shopCart.shopcar_remove, {
                        //'goodsId': target.goodsId
                        id: target.id
                    }).then(res => {
                        if (res.succeed) {
                            this.getCarts();
                            setTimeout(() => {
                                app.addCurUserShopCar(-1);
                            }, 1);
                        } else {
                            utils.showToastErr(res.msg);
                        }
                    });
                }
            })
    }

    public bindCountInput(e) {
        const count = Math.abs(e.detail.value);
        this.setCount(e.currentTarget.dataset, count);
    }

    public decrease(e) {
        const count = Math.abs(e.currentTarget.dataset.count - 1);
        this.setCount(e.currentTarget.dataset, count);
    }

    public increase(e) {
        const count = Math.abs(e.currentTarget.dataset.count + 1);
        this.setCount(e.currentTarget.dataset, count);
    }

    setCount(target: { index?: number }, count: number) {
        const carts = this.data.carts.items;
        let cartItem: ShopCart = carts[target.index];
        cartItem.count = count;
        cartItem.count = cartItem.count < 1 ? 1 : cartItem.count;
        this.setData({
            'carts.items': carts
        });
        this.getTotalPrice();
    }

    getSelectedGoods(): Array<ShopCart> {
        const carts = this.data.carts.items;
        let checkedList = [];
        const checkeds = __.where(carts, { 'selected': true });
        if (checkeds && checkeds.length > 0) {
            checkedList = __.union(checkedList, checkeds);
        }
        return checkedList;
    }

    getTotalPrice() {
        const carts = this.getSelectedGoods();
        let total = 0;
        const that = this;
        let count = 0;
        __.each(carts, (item: ShopCart) => {
            count += item.count;
            total += item.count * item.unitPrice;
        });
        this.setData({
            'carts.total': tools.toMoney(total), //Math.round(total * 100) / 100,
            'carts.selectedCount': count,
        })
    }

    touchend(e) {
        this.setData({
            'isTouchMove': false
        })
    }

    touchstart(e) {
        if (this.data.isTouchMove || !this.isIos) {
            return;
        }
        this.setData({
            'isTouchMove': true
        })
        this.data.carts.items.forEach((v: any, i) => {
            v['isTouchMove'] = false;
        })
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            'carts.items': this.data.carts.items
        })
    }

    touchmove(e) {
        if (!this.isIos) {
            return;
        }
        const index = e.currentTarget.dataset.index;
        const startX = this.data.startX;
        const startY = this.data.startY;
        const touchMoveX = e.changedTouches[0].clientX;
        const touchMoveY = e.changedTouches[0].clientY;
        const angle = this.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        if (Math.abs(angle) > 30) {
            return;
        }
        let t = true;
        if (touchMoveX > startX) {
            t = false;
        }
        this.data.carts.items[index]['isTouchMove'] = t;
        this.data.carts.items[index]['isTouchMove'] = t;
        this.setData({
            'carts.items': this.data.carts.items
        })
    }

    angle(start, end) {
        let _X = end.X - start.X;
        let _Y = end.Y - start.Y;
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    }

    longPressEvent(e) {
        if (this.isIos) {
            return;
        }
        const dd = wux.actionSheet.show({
            cancelText: '取消',
            cancel() { },
            destructiveText: '删除',
            destructiveButtonClicked: () => {
                this.delCartItem(e);
                return true;
            }
        })
        // wxService.showActionSheet({ itemList: ['移除'], itemColor: '#1724ff' })
        //     .then((res: wx.ShowActionSheetResult) => {
        //         if (res.tapIndex == 0) {
        //             this.delCartItem(e)
        //         }
        //     }).catch(e=>{

        //     })

    }
}

Page(new CartListPage());
